package com.biscuit.page.basicservice.design.verify_code.publish.strategy;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.biscuit.page.basicservice.design.verify_code.publish.VerifyCodePublishAbstractDTO;
import com.biscuit.page.basicservice.design.verify_code.publish.VerifyCodePublishContext;
import com.biscuit.page.basicservice.design.verify_code.publish.VerifyCodePublishType;
import com.biscuit.page.basicservice.design.verify_code.publish.VerifyCodePublishTypeEnum;
import com.biscuit.page.basicservice.model.entities.mysql.SysNoteMessage;
import com.biscuit.page.basicservice.persistence.dao.NoteMessageDao;
import com.biscuit.page.basicservice.service.AliyunService;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;
import com.biscuit.page.basicservice.utils.BaseThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author biscuit
 * @createTime 2024/6/25 11:43
 */
@Slf4j
@Component
@VerifyCodePublishType(type = VerifyCodePublishTypeEnum.MOBILE)
public class MobileVerifyCodePublishHandlerStrategy extends AbstractVerifyCodePublishStrategy {

    @Resource
    private AliyunService aliyunService;

    @Resource
    private NoteMessageDao noteMessageDao;

    @Override
    public void publish(VerifyCodePublishContext context) {
        // 调用装饰者超类，执行前置通用逻辑
        VerifyCodePublishAbstractDTO dto = super.publishBefore(context);

        // 记录短信验证码发送记录
        SysNoteMessage data = new SysNoteMessage();
        data.setMobile(context.getAccount());
        data.setIp(context.getIp());
        data.setVerifyCode(dto.getVerifyCode());
        this.noteMessageDao.insertAndIncrement(data);

        // 异步向指定手机号发送验证码邮件
        BaseThreadUtil.async(() -> {
            try {
                // 发送验证码
                SendSmsResponse response = this.aliyunService.noteVerifyCodePublish(
                        context.getAccount(),
                        dto.getVerifyCode());

                // 修改短信验证码状态
                this.noteMessageDao.updateResultById(data.getId(), 0, JSON.toJSONString(response.getBody()));
            } catch (Exception e) {
                this.noteMessageDao.updateResultById(data.getId(), 0, e.getMessage());
            }
        });
        log.info("MobileVerifyCodePublishHandlerStrategy publish，向手机号 {} 发送验证码 {}", context.getAccount(), dto.getVerifyCode());

        // 调用装饰者超类，执行后置通用逻辑
        super.publishAfter(dto);
    }

}
